package life.system.order.interceptor;

import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 在执行目标方法之前，判断用户的登录状态，并封装传递给目标请求
 */
public class LoginUserInterceptor implements HandlerInterceptor {

    // ThreadLocal同一个线程共享数据
    public static ThreadLocal<String> loginUser = new ThreadLocal<>();

    /**
     * 在目标方法之前拦截
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        // 过滤 /order/order/status/** 请求
        String uri = request.getRequestURI();
        AntPathMatcher matcher = new AntPathMatcher();
        boolean status = new AntPathMatcher().match("/order/order/app/**", uri);
        boolean orderReturn = new AntPathMatcher().match("/order/orderreturnapply/app/**", uri);
        boolean payed = matcher.match("/payed/**", uri);
        if (status || payed || orderReturn) {
            String token = request.getHeader("token");
            if (token != null) {
                loginUser.set(token);
                return true;
            } else {
                return false;
            }
        }
        return true;
    }
}
